import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login/Login.vue'
import Reg from '../views/Reg/Reg.vue'
import main from '../views/main/main.vue'
import store from '../store'
import Home from '@/views/Menus/Home/Home.vue'

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: main,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const whiteList = ['/login', '/reg']

  if (!store.state.user.token && !whiteList.includes(to.path)) {
    Vue.prototype.$message.error('您没有登录')
    return next('/login')
  }
  next()
})

export default router
